package com.bpf.base.controller.system;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bpf.base.util.AjaxUtils;
import com.bpf.base.util.Collections3;
import com.bpf.base.util.ExcelUitl;
import com.bpf.base.util.MapUtil;
import com.bpf.base.cache.AppService;
import com.bpf.base.common.Constants;
import com.bpf.base.controller.BaseController;
import com.bpf.base.model.system.Role2MenuExample;
import com.bpf.base.model.system.TSysMenu;
import com.bpf.base.base.exception.BusinessException;
import com.bpf.base.base.vo.TreeNode;
import com.bpf.base.bean.system.TSysMenuForm;
import com.bpf.base.service.system.Role2MenuService;
import com.bpf.base.service.system.TSysMenuService;

/**
 * @date 2016-07-20 09:51:17
 */
@Controller
@RequestMapping(value = {"/system/menu"})
public class TSysMenuController extends BaseController{
	private Logger logger = LoggerFactory.getLogger(TSysMenuController.class);

    @Resource
	private TSysMenuService tSysMenuService;
	
    @Autowired
	private AppService appService;

	@Autowired
	private Role2MenuService role2MenuService;

    
    
    @RequestMapping(value = { "/init", "" })
	public String init(HttpServletRequest request) {
		request.setAttribute("enabledList", appService.asMap().get("IS_ENABLED"));
		return "system/menu";
	}

    /**
	 * 根据条件查询
	 * @param params
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping("/getTSysMenuList")
	@ResponseBody
	public Map<String, Object> getTSysMenuList(HttpServletRequest request, TSysMenuForm form,String jsonpCallback){
		Integer pageNum = Integer.parseInt(null == request.getParameter("page") ? 1 + "" : request.getParameter("page").toString());
		Integer pageSize = Integer.parseInt(null == request.getParameter("rows") ? 10 + "" : request.getParameter("rows").toString());
		Map<String, Object> params = new HashMap<String, Object>();
		params = MapUtil.toMap(form);
		params.put("offset", (pageNum-1)*pageSize);
		params.put("limit", pageSize);
		return tSysMenuService.getTSysMenuList(params);
	}    
  
  	@RequestMapping("/addTSysMenu")
	@ResponseBody
	public Map<String, Object> addTSysMenu(HttpServletRequest request, TSysMenu form,String jsonpCallback) throws UnsupportedEncodingException{
		Map<String, Object> params = new HashMap<String, Object>();
		// 参数检查
		params = MapUtil.toMap(form);
		// 调用service
		if(tSysMenuService.addTSysMenu(params)>0)
			return AjaxUtils.reponseToJson(Constants.Action.SAVE, true);
		else
			return AjaxUtils.reponseToJson(Constants.Action.SAVE, false);
	}
	
	/**
	 * 更新
	 * @param params
	 * @return
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws JSONException
	 */
	@RequestMapping("/updateTSysMenu")
	@ResponseBody
	public Map<String, Object> updateTSysMenu( TSysMenu form,String jsonpCallback) throws InstantiationException, IllegalAccessException{
		// 参数检查
		TSysMenu tSysMenu = MapUtil.toObject(TSysMenu.class, MapUtil.toMap(form));
		// 调用service
		if(tSysMenuService.updateTSysMenu(tSysMenu) > 0)
			return AjaxUtils.reponseToJson(Constants.Action.UPDATE, true);
		else
			return AjaxUtils.reponseToJson(Constants.Action.UPDATE, false);
	}
	
	/**
	 * 删除
	 * @param params
	 * @return
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws JSONException
	 */
	@RequestMapping("/deleteTSysMenu")
	@ResponseBody
	public Map<String, Object> deleteTSysMenu(HttpServletRequest request,String jsonpCallback) throws InstantiationException, IllegalAccessException{
		String[] idArray=request.getParameterValues("idArray[]");
		// 调用service
		if(tSysMenuService.delTSysMenuBat(idArray) > 0){
			return AjaxUtils.reponseToJson(Constants.Action.DELETE, true);
		}else{
			return AjaxUtils.reponseToJson(Constants.Action.DELETE, false);
		}
	}
	
	@RequestMapping("/exporttSysMenu")
	public void exportTSysMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		OutputStream out = response.getOutputStream();
		String title = "业主信息";
		String[] headers = { "住户编号", "业主姓名", "房产证", "土地证", "性别", "身份证", "联系电话" };
		String[] columns = { "id", "name", "housePropertyCert", "landCert", "gender", "idNo", "mobile" };
		List<TSysMenu> houseList = tSysMenuService.getAllTSysMenu(null);
		ExcelUitl<TSysMenu> excelUtil = new ExcelUitl<TSysMenu>();
		String pattern = "yyyy-MM-dd HH:mm:dd";
		response.setHeader("Content-Disposition", "attachment;filename=" + new String((title + ".xls").getBytes(), "iso-8859-1"));
		excelUtil.exportoExcel(title, headers, columns, houseList, out, pattern);
	}
	
	@ResponseBody
	@RequestMapping(value = "/list")
	public List<TSysMenu> list(HttpServletRequest request) {
		List<TSysMenu> list = new ArrayList<TSysMenu>();
		// 所有菜单
		List<TSysMenu> allMenu = tSysMenuService.selectList(null);

		// 1为默认根节点 菜单树,2为工况模板根节点
		TSysMenu rootMenu;
		if (request.getParameter("menuId") != null && !"".equals(request.getParameter("menuId"))) {
			Integer menuId = Integer.parseInt(request.getParameter("menuId"));
			rootMenu = tSysMenuService.selectByPrimaryKey(menuId);
		} else {
			rootMenu = tSysMenuService.selectByPrimaryKey(1);
		}

		// top菜单
		List<TSysMenu> topMenuList = tSysMenuService.selectByParentMenuId(rootMenu.getMenuId());

		// top二级菜单
		List<TSysMenu> top2MenuList = tSysMenuService.selectByParentMenuId(rootMenu.getMenuId());

		// 左边的菜单
		List<TSysMenu> tempLeftMenuList = new ArrayList<TSysMenu>();

		// 为top菜单添加top2菜单
		if (!Collections3.isEmpty(topMenuList)) {
			List<TSysMenu> topTMenuList;
			for (TSysMenu topMenu : topMenuList) {
				topTMenuList = new ArrayList<TSysMenu>();
				for (TSysMenu menu : allMenu) {
					if (menu.getMenuParentId().equals(topMenu.getMenuId())) {
						topTMenuList.add(menu);
						top2MenuList.add(menu);
					}
				}
				topMenu.setChildren(topTMenuList);
			}
		}

		// 为top2菜单添加左边子菜单
		if (!Collections3.isEmpty(top2MenuList)) {
			List<TSysMenu> leftMenuList;
			for (TSysMenu topMenu : top2MenuList) {
				leftMenuList = new ArrayList<TSysMenu>();
				for (TSysMenu menu : allMenu) {
					if (menu.getMenuParentId().equals(topMenu.getMenuId())) {
						leftMenuList.add(menu);
						tempLeftMenuList.add(menu);
					}
				}
				topMenu.setChildren(leftMenuList);
			}
		}

		// 为left的菜单的添加子菜单
		if (!Collections3.isEmpty(tempLeftMenuList)) {
			List<TSysMenu> leftChildMenuList;
			for (TSysMenu leftMenu : tempLeftMenuList) {
				leftChildMenuList = new ArrayList<TSysMenu>();
				for (TSysMenu menu : allMenu) {
					if (menu.getMenuParentId().equals(leftMenu.getMenuId())) {
						leftChildMenuList.add(menu);
					}
				}
				leftMenu.setChildren(leftChildMenuList);
			}
		}

		rootMenu.setChildren(topMenuList);
		list.add(rootMenu);
		return list;
	}

	@ResponseBody
	@RequestMapping(value = "/tree")
	public List<TreeNode> tree() {
		List<TreeNode> list = new ArrayList<TreeNode>();
		// 所有菜单
		List<TSysMenu> allMenu = tSysMenuService.selectList(null);

		// 1为默认根节点 菜单树
		TSysMenu rootMenu = tSysMenuService.selectByPrimaryKey(1);
		TreeNode rootNode = new TreeNode();
		rootNode.setId(String.valueOf(rootMenu.getMenuId()));
		rootNode.setText(rootMenu.getMenuName());

		// top菜单
		List<TSysMenu> topMenuList = tSysMenuService.selectByParentMenuId(rootMenu.getMenuId());

		List<TreeNode> topNodeList = new ArrayList<TreeNode>();
		TreeNode topNode;
		for (TSysMenu topMenu : topMenuList) {
			topNode = new TreeNode();
			topNode.setId(String.valueOf(topMenu.getMenuId()));
			topNode.setText(topMenu.getMenuName());
			topNodeList.add(topNode);
		}

		// 上边二级菜单
		List<TreeNode> tempTop2NodeList = new ArrayList<TreeNode>();
		// 为top菜单添加左边子菜单
		if (!Collections3.isEmpty(topNodeList)) {
			List<TreeNode> topTNodeList;
			for (TreeNode treeNode : topNodeList) {
				topTNodeList = new ArrayList<TreeNode>();
				for (TSysMenu menu : allMenu) {
					TreeNode topTNode;
					if (menu.getMenuParentId().equals(Integer.parseInt(treeNode.getId()))) {
						topTNode = new TreeNode();
						topTNode.setId(String.valueOf(menu.getMenuId()));
						topTNode.setText(menu.getMenuName());
						topTNodeList.add(topTNode);
						tempTop2NodeList.add(topTNode);
					}
				}
				treeNode.setChildren(topTNodeList);
			}
		}

		// 左边的菜单
		List<TreeNode> tempLeftNodeList = new ArrayList<TreeNode>();
		// 为top菜单添加左边子菜单
		if (!Collections3.isEmpty(tempTop2NodeList)) {
			List<TreeNode> leftNodeList;
			for (TreeNode treeNode : tempTop2NodeList) {
				leftNodeList = new ArrayList<TreeNode>();
				for (TSysMenu menu : allMenu) {
					TreeNode leftNode;
					if (menu.getMenuParentId().equals(Integer.parseInt(treeNode.getId()))) {
						leftNode = new TreeNode();
						leftNode.setId(String.valueOf(menu.getMenuId()));
						leftNode.setText(menu.getMenuName());
						leftNodeList.add(leftNode);
						tempLeftNodeList.add(leftNode);
					}
				}
				treeNode.setChildren(leftNodeList);
			}
		}

		// 为left的菜单的添加子菜单
		if (!Collections3.isEmpty(tempLeftNodeList)) {
			List<TreeNode> leftChildNodeList;
			for (TreeNode treeNode : tempLeftNodeList) {
				leftChildNodeList = new ArrayList<TreeNode>();
				for (TSysMenu menu : allMenu) {
					TreeNode leftChildrenNode;
					if (menu.getMenuParentId().equals(Integer.parseInt(treeNode.getId()))) {
						leftChildrenNode = new TreeNode();
						leftChildrenNode.setId(String.valueOf(menu.getMenuId()));
						leftChildrenNode.setText(menu.getMenuName());
						leftChildNodeList.add(leftChildrenNode);
					}
				}
				treeNode.setChildren(leftChildNodeList);
			}
		}
		rootNode.setChildren(topNodeList);
		list.add(rootNode);
		return list;
	}

	@ResponseBody
	@RequestMapping(value = "/getByRole")
	public Map<String, Object> getByRole(@RequestParam(value = "roleId") Integer roleId) {
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		List<TSysMenu> menus = tSysMenuService.selectByRoleId(roleId);
		List<TSysMenu> list = new ArrayList<TSysMenu>();
		TSysMenu menu;
		for (TSysMenu m : menus) {
			menu = new TSysMenu();
			menu.setMenuId(m.getMenuId());
			list.add(menu);
		}
		map.put("rows", list);
		return map;

	}

	@ResponseBody
	@RequestMapping(value = "/isLeaf")
	public Boolean isLeaf(@RequestParam(value = "menuParentId", required = true) Integer menuParentId) {
		// 所有菜单
		List<TSysMenu> allMenu = tSysMenuService.selectList(null);

		// top菜单
		List<TSysMenu> topMenuList = tSysMenuService.selectByParentMenuId(1);

		// 得到top1的所有菜单ID
		List<Integer> topMenuIdList = new ArrayList<Integer>();
		for (TSysMenu menu : topMenuList) {
			topMenuIdList.add(menu.getMenuId());
		}
		
		TSysMenuForm top2menuForm= new TSysMenuForm();
		top2menuForm.setMenuParentIdList(topMenuIdList);
		// 得到top2的所有菜单
		List<TSysMenu> top2MenuList = tSysMenuService.getAllTSysMenu(MapUtil.toMap(top2menuForm));
		// 得到top1的所有菜单ID
		List<Integer> top2MenuIdList = new ArrayList<Integer>();
		for (TSysMenu menu : top2MenuList) {
			top2MenuIdList.add(menu.getMenuId());
		}
		
		TSysMenuForm menuForm= new TSysMenuForm();
		menuForm.setMenuParentIdList(top2MenuIdList);
		List<TSysMenu> tempLeftMenuList = tSysMenuService.getAllTSysMenu(MapUtil.toMap(menuForm));
		// 判断是否是左侧菜单子菜单
		for (TSysMenu menu : tempLeftMenuList) {
			if (menuParentId.equals(menu.getMenuId())) {
				return true;
			}
		}
		return false;

	}

	@ResponseBody
	@RequestMapping(value = "/save")
	public Map<String, Object> save(TSysMenu value, HttpServletRequest request) {
		// 添加菜单设置索引顺序
		Integer maxOrderIndex = tSysMenuService.selectMaxOrder(value.getMenuParentId());
		value.setMenuOrder(maxOrderIndex + 1);
		if (tSysMenuService.addTSysMenu(MapUtil.toMap(value)) > 0) {
			if (request.getParameter("mnt") != null) {
				TSysMenu menuModelParent = tSysMenuService.selectByPrimaryKey(value.getMenuParentId());
				TSysMenuForm form = new TSysMenuForm();
				form.setMenuName(menuModelParent.getMenuName());
				form.setMenuIdNotEqualTo(menuModelParent.getMenuId());
				TSysMenu menuEidtParent = tSysMenuService.getAllTSysMenu(MapUtil.toMap(form)).get(0);
				value.setMenuId(null);
				value.setMenuParentId(menuEidtParent.getMenuId());
				tSysMenuService.addTSysMenu(MapUtil.toMap(value));
			}
			return AjaxUtils.reponseToJson(Constants.Action.SAVE, true);
		}
		return AjaxUtils.reponseToJson(Constants.Action.SAVE, false);
	}

	@ResponseBody
	@RequestMapping(value = "/update")
	public Map<String, Object> update(TSysMenu value, HttpServletRequest request) {
		if (tSysMenuService.updateTSysMenu(value) > 0) {
			if (request.getParameter("mnt") != null) {
				value.setMenuId(value.getMenuId() + 21);
				value.setMenuParentId(value.getMenuParentId() + 21);
				tSysMenuService.updateTSysMenu(value);
			}
			return AjaxUtils.reponseToJson(Constants.Action.UPDATE, true);
		}
		return AjaxUtils.reponseToJson(Constants.Action.UPDATE, false);

	}

	@ResponseBody
	@RequestMapping(value = "/hasChildren")
	public Boolean hasChildren(@RequestParam(value = "menuId", required = true) Integer menuId) {
		TSysMenuForm form = new TSysMenuForm();
		form.setMenuParentId(menuId);
		return Collections3.isEmpty(tSysMenuService.getTSysMenuList(MapUtil.toMap(form)));

	}

	@RequestMapping(value = "/deleteAll")
	@ResponseBody
	public Map<String, Object> delete(@RequestParam(value = "menuId", required = true) Integer menuId) {
		TSysMenuForm form = new TSysMenuForm();
		form.setMenuId(menuId);
		if (tSysMenuService.delTSysMenu(MapUtil.toMap(form)) > 0) {
			// 删除角色关联的菜单信息
			Role2MenuExample role2MenuExample = new Role2MenuExample();
			role2MenuExample.createCriteria().andMenuIdEqualTo(menuId);
			role2MenuService.deleteByExample(role2MenuExample);
			return AjaxUtils.reponseToJson(Constants.Action.DELETE, true);
		}
		return AjaxUtils.reponseToJson(Constants.Action.DELETE, false);

	}

	@ResponseBody
	@RequestMapping(value = "/getMinOrder/{menuParentId}")
	public Integer getMinOrder(@PathVariable(value = "menuParentId") Integer menuParentId) {
		return tSysMenuService.selectMinOrder(menuParentId);
	}

	@ResponseBody
	@RequestMapping(value = "/getMaxOrder/{menuParentId}")
	public Integer getMaxOrder(@PathVariable(value = "menuParentId") Integer menuParentId) {
		return tSysMenuService.selectMaxOrder(menuParentId);

	}

	@ResponseBody
	@RequestMapping("/arrowUp/{menuId}/{menuParentId}")
	public void arrowUp(@PathVariable(value = "menuId") Integer menuId, @PathVariable(value = "menuParentId") Integer menuParentId) throws BusinessException {
		TSysMenuForm form = new TSysMenuForm();
		form.setMenuParentId(menuParentId);
		List<TSysMenu> menus = tSysMenuService.getAllTSysMenu(MapUtil.toMap(form));
		for (int i = 0; i < menus.size(); i++) {
			Integer temp;
			if (menuId.equals(menus.get(i).getMenuId())) {
				temp = menus.get(i).getMenuOrder();
				menus.get(i).setMenuOrder(menus.get(i - 1).getMenuOrder());
				menus.get(i - 1).setMenuOrder(temp); // 交换位置后更新
				//tSysMenuService.updateByPrimaryKeySelective(menus.get(i));
				tSysMenuService.updateTSysMenu(menus.get(i));
				tSysMenuService.updateTSysMenu(menus.get(i - 1));
				//tSysMenuService.updateByPrimaryKeySelective(menus.get(i - 1));
			}
		}

	}

	@ResponseBody
	@RequestMapping("/arrowDown/{menuId}/{menuParentId}")
	public void arrowDown(@PathVariable(value = "menuId") Integer menuId, @PathVariable(value = "menuParentId") Integer menuParentId) throws BusinessException {
		TSysMenuForm form = new TSysMenuForm();
		form.setMenuParentId(menuParentId);
		List<TSysMenu> menus = tSysMenuService.getAllTSysMenu(MapUtil.toMap(form));
		for (int i = 0; i < menus.size(); i++) {
			Integer temp;
			if (menuId.equals(menus.get(i).getMenuId())) {
				temp = menus.get(i).getMenuOrder();
				menus.get(i).setMenuOrder(menus.get(i + 1).getMenuOrder());
				menus.get(i + 1).setMenuOrder(temp); // 交换位置后更新
				tSysMenuService.updateTSysMenu(menus.get(i));
				tSysMenuService.updateTSysMenu(menus.get(i + 1));
			}
		}
	}

	@ResponseBody
	@RequestMapping("/lock/{menuId}/{status}")
	public void arrowDown(@PathVariable(value = "menuId") Integer menuId, @PathVariable(value = "status") String status) throws BusinessException {
		TSysMenu menu = new TSysMenu();
		menu.setStatus(status);
		menu.setMenuId(menuId);
		tSysMenuService.updateTSysMenu(menu);
	}

}
